<template>
  <div class="common-layout">
    <el-container>
      <el-header>
        <div>
          <el-row :gutter="30">
            <el-col :span="7">
              <el-input
                placeholder="客户姓名"
                @clear="query"
                v-model="condition.customerName"
                clearable
                size="large"
              >
                <template #append>
                  <el-button type="info" @click="query" style="color:black">查询</el-button>
                </template>
              </el-input>
            </el-col>
			<el-col :span="17" v-if="roleId===2">
			  <el-button type="primary" @click="addItem" color="#337ab7" style="margin-top:4px">
			    <el-icon>
			      <Plus />
			    </el-icon>
			    <span>添加外出申请</span>
			  </el-button>
			</el-col>
          </el-row>
        </div>
      </el-header>
      <el-divider style="margin:0"></el-divider>
      <el-main>
        <el-row :gutter="20">
          <el-col :span="9">
            <div class="table-main">
              <div class="table-main-header">客户信息</div>
              <!-- 表格 -->
              <el-table
                :data="khxxList"
                highlight-current-row
                @current-change="handleChangeCustomer"
                size="small"
                style="width: 100% ;color:black;"
                stripe
              >
                <el-table-column
                  align="center"
                  fixed
                  type="index"
                  :index="indexMethod"
                  label="序号"
                  width="40"
                />
                <el-table-column align="center" prop="customerName" label="姓名"/>
                <el-table-column align="center" prop="customerAge" label="年龄"/>
                <el-table-column align="center" prop="customerSex" label="性别">
                  <template #default="scope">{{ scope.row.customerSex==0?'男':'女'}}</template>
                </el-table-column>
                <el-table-column align="center" prop="bedNo" label="床号"/>
                <el-table-column align="center" prop="levelName" label="护理级别" />
              </el-table>
              <!-- 分页插件 -->
              <div style="margin-top:15px">
                <el-pagination
                  :page-size="page.pageSize"
                  background
                  :current-page="page.currentPag"
                  layout=" prev, pager, next"
                  :total="page.total"
                  @current-change="handleCurrentChange"
                />
              </div>
            </div>
          </el-col>
          <el-col :span="15">
            <div class="table-main">
              <div class="table-main-header">外出登记</div>
              <!-- 表格 -->
              <el-table :data="outwardList" size="small">
                <el-table-column
                  align="center"
                  :index="indexMethodRecord"
                  type="index"
                  label="序号"
                  width="40"
                />
                <el-table-column align="center" prop="customerName" label="客户名称" width="100" />
                <el-table-column align="center" prop="outgoingreason" label="外出事由" width="100" />
                <el-table-column align="center" prop="outgoingtime" label="外出时间" width="70" />
                <el-table-column align="center" prop="expectedreturntime" label="预计回院时间" width="100" />
                <el-table-column align="center" prop="actualreturntime" label="实际回院时间" width="100" />
                <el-table-column align="center" prop="escorted" label="陪同人" width="100" />
				<el-table-column align="center" prop="relation" label="与老人关系" width="100" />
				<el-table-column align="center" prop="escortedtel" label="陪同人电话" width="100" />
                <el-table-column align="center" prop="auditstatus" label="审批状态" width="100">
					<template #default="{row}">
						{{row.auditstatus===0?'已提交':row.auditstatus===1?'同意':'拒绝'}}
					</template>
				</el-table-column>
                <el-table-column align="center" label="操作" width="100">
                  <template #default="scope">
                    <el-button v-if="scope.row.auditstatus === 1 && roleId === 2" :disabled="scope.row.actualreturntime" type="success" size="small" round plain @click="updateTime(scope.row.id)">登记回院时间</el-button>
					<el-button  v-if="scope.row.auditstatus === 0 && roleId === 2" type="danger" size="small" round plain @click="del(scope.row.id)">撤销申请</el-button>
					<el-button  v-if="scope.row.auditstatus === 0 && roleId !== 2" type="primary" size="small" round plain @click="examine(scope.row.id)">审批</el-button>
                  </template>
                </el-table-column>
              </el-table>
              <!-- 分页插件 -->
              <div style="margin-top:15px" v-if="outwardList.length>0">
                <el-pagination
                  :page-size="pageRecord.pageSize"
                  background
                  :current-page="pageRecord.currentPag"
                  layout=" prev, pager, next"
                  :total="pageRecord.total"
                  @current-change="handleRecordChange"
                />
              </div>
            </div>
          </el-col>
        </el-row>
      </el-main>
    </el-container>
	<!-- 修改/添加对话框 -->
	<el-dialog
	  v-model="dialog.dialogTimeVisible"
	  :title="dialog.tops"
	  width="40%"
	  align-center
	  draggable
	  :before-close="handleTimeClose"
	>
	  <el-divider border-style="double" style="margin:0;" />
	  <el-form
	    label-position="right"
	    label-width="auto"
	    style="max-width:380px;margin:20px auto"
	    class="demo-form-inline"
	    ref="itemTimeFormRef"
	    :model="dialog.item"
	    :rules="rules"
	  >
	 
	    <el-form-item label="实际回院时间： " prop="actualreturntime">
			<el-date-picker
					style="width:320px" 
			        v-model="dialog.item.actualreturntime"
			        type="date"
			        placeholder="实际回院时间:"
					value-format="YYYY-MM-DD"
			      />
	    </el-form-item>
		
	  </el-form>
	  <el-divider border-style="double" style="margin:0;" />
	  <template #footer>
	    <span class="dialog-footer" style="padding-top: 0px">
	      <el-button type="primary" @click="handleBackTimeUpdate">保存</el-button>
	      <el-button @click="cancelTime">取消</el-button>
	    </span>
	  </template>
	</el-dialog>
	<!-- 修改/添加对话框 -->
	<el-dialog
	  v-model="dialog.dialogExamineVisible"
	  :title="dialog.tops"
	  width="40%"
	  align-center
	  draggable
	  :before-close="handleExamineClose"
	>
	  <el-divider border-style="double" style="margin:0;" />
	  <el-form
	    label-position="right"
	    label-width="auto"
	    style="max-width:380px;margin:20px auto"
	    class="demo-form-inline"
	    ref="itemExamineFormRef"
	    :model="dialog.item"
	    :rules="rules"
	  >
	 
	    <el-form-item label="审批：" prop="auditStatus">
			<el-radio-group v-model="dialog.item.auditStatus" class="ml-4">
			      <el-radio :label="1">同意</el-radio>
			      <el-radio :label="2">拒绝</el-radio>
			</el-radio-group>
	    </el-form-item>
		
	  </el-form>
	  <el-divider border-style="double" style="margin:0;" />
	  <template #footer>
	    <span class="dialog-footer" style="padding-top: 0px">
	      <el-button type="primary" @click="submitExamine">保存</el-button>
	      <el-button @click="cancelExamine">取消</el-button>
	    </span>
	  </template>
	</el-dialog>
	<!-- 修改/添加对话框 -->
	<el-dialog
	  v-model="dialog.dialogVisible"
	  :title="dialog.tops"
	  width="40%"
	  align-center
	  draggable
	  :before-close="handleClose"
	>
	  <el-divider border-style="double" style="margin:0;" />
	  <el-form
	    label-position="right"
	    label-width="auto"
	    style="max-width:380px;margin:20px auto"
	    class="demo-form-inline"
	    ref="itemFormRef"
	    :model="dialog.item"
	    :rules="rules"
	  >
	    <el-form-item label="客户姓名：" prop="customerId">
			<el-select v-model="dialog.item.customerId" style="width:320px" placeholder="客户姓名：">
			  <el-option v-for="item in customerList" :key="item.id" :label="item.customerName" :value="item.id" />
			</el-select>
	    </el-form-item>
		<el-form-item label="外出事由：" prop="outgoingreason">
		  <el-input v-model="dialog.item.outgoingreason" />
		</el-form-item>
	    <el-form-item label="外出时间：" prop="outgoingtime">
			<el-date-picker
					style="width:320px" 
			        v-model="dialog.item.outgoingtime"
			        type="date"
			        placeholder="外出时间:"
					value-format="YYYY-MM-DD"
			      />
	    </el-form-item>
		
	    <el-form-item label="预计回院时间： " prop="expectedreturntime">
			<el-date-picker
					style="width:320px" 
			        v-model="dialog.item.expectedreturntime"
			        type="date"
			        placeholder="外出时间:"
					value-format="YYYY-MM-DD"
			      />
	    </el-form-item>
		
		<el-form-item label="陪同人： " prop="escorted">
		  <el-input v-model="dialog.item.escorted" />
		</el-form-item>
		
		<el-form-item label="陪同人电话： " prop="escortedtel">
		  <el-input v-model="dialog.item.escortedtel" />
		</el-form-item>
	  </el-form>
	  <el-divider border-style="double" style="margin:0;" />
	  <template #footer>
	    <span class="dialog-footer" style="padding-top: 0px">
	      <el-button type="primary" @click="save">保存</el-button>
	      <el-button @click="cancel">取消</el-button>
	    </span>
	  </template>
	</el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';
import { getKhxxList } from "@/api/customerApi.js";
import { queryOutwardVo, addOutward, examineOutward, delOutward, updateBackTime } from "@/api/outwardApi.js";
import { getSessionStorage, getCurDate } from '@/utils/common.js';

// 表单引用
const itemFormRef = ref(null);
const itemExamineFormRef = ref(null);
const itemTimeFormRef = ref(null);

// 响应式状态
const khxxList = ref([]);
const outwardList = ref([]);
const customerList = ref([]);
const roleId = ref('');

// 查询条件封装--客户
const condition = reactive({
    customerName: "",
    userId: "",
    pageSize: "1" // 默认第一页
});

// 查询条件封装--外出记录
const conditionRecord = reactive({
    userId: "",
    pageSize: "1" // 默认第一页
});

// 分页属性封装 --客户
const page = reactive({
    total: 0,
    pageSize: 6,
    currentPag: 1,
    pagCount: 0
});

// 分页属性封装 --外出记录
const pageRecord = reactive({
    total: 0,
    pageSize: 6,
    currentPag: 1,
    pagCount: 0
});

// 模态框数据
const dialog = reactive({
    dialogVisible: false, // 模态框状态
    dialogTimeVisible: false, // 模态框状态
    dialogExamineVisible: false,
    tops: "", // 模态框标题
    item: {
        id: "",
        username: "",
        nickname: "",
        sex: "",
        email: "",
        phoneNumber: "",
        isDeleted: "", // 状态 1: 启用; 2: 停用
        createTime: "",
        createBy: "",
        password: "",
        roleId: "",
        auditstatus: 0,
        actualreturntime: "",
        backTimeId: "",
        auditperson: "",
        audittime: ""
    },
    statusArr: [
        {
            value: 1,
            label: "停用",
        },
        {
            value: 2,
            label: "启用"
        }
    ]
});

// 校验规则
const rules = reactive({
    // 可以根据需要添加校验规则
});

// 计算属性
const indexMethod = computed(() => {
    return page.currentPag * page.pageSize - page.pageSize + 1;
});

const indexMethodRecord = computed(() => {
    return pageRecord.currentPag * pageRecord.pageSize - pageRecord.pageSize + 1;
});

// 点击查询
const query = () => {
    // 清空护理记录数据表
    outwardList.value = [];
    
    condition.pageSize = "1"; // 回到第一页
    fetchKhxxList();
    queryOutwardVoData();
};

// 选中页码-客户
const handleCurrentChange = (curPage) => {
    page.currentPag = curPage;
    condition.pageSize = curPage; // 参数pageSize是服务端接收页码参数名
    // 重新渲染表格
    fetchKhxxList();
    // 清空护理记录数据表
    outwardList.value = [];
    conditionRecord.customerId = "";
};

// 处理客户表格行选中
const handleChangeCustomer = (row) => {
    if (row != null) {
        // 点击页码会清空 row 因此做出判断逻辑
        // 构建查询条件
        conditionRecord.userId = row.id;
        queryOutwardVoData();
    }
};

// 选中页码-外出记录
const handleRecordChange = (curPage) => {
    pageRecord.currentPag = curPage;
    conditionRecord.pageSize = curPage; // 参数 pageSize 是服务端接收页码参数名
    // 重新渲染表格:
    queryOutwardVoData();
};

// 审批操作
const examine = (id) => {
    dialog.tops = "审批";
    dialog.dialogExamineVisible = true;
    dialog.item.id = id;
};

// 审批对话框关闭处理
const handleExamineClose = () => {
    dialog.dialogExamineVisible = false;
    resetForm(itemExamineFormRef); // 重置表单
};

// 取消审批
const cancelExamine = () => {
    handleExamineClose();
};

// 更新回院时间
const updateTime = (id) => {
    dialog.tops = "修改实际回院时间";
    dialog.dialogTimeVisible = true;
    dialog.item.backTimeId = id;
};

// 时间修改对话框关闭处理
const handleTimeClose = () => {
    dialog.dialogTimeVisible = false;
    resetForm(itemTimeFormRef); // 重置表单
};

// 取消修改时间
const cancelTime = () => {
    handleTimeClose();
};

// 添加外出申请
const addItem = () => {
    dialog.tops = "添加外出申请";
    dialog.dialogVisible = true;
};

// 对话框关闭处理
const handleClose = () => {
    dialog.dialogVisible = false;
    resetForm(itemFormRef); // 重置表单
};

// 取消操作
const cancel = () => {
    handleClose();
};

// 重置表单
const resetForm = (formRef) => {
    if (formRef.value) {
        formRef.value.resetFields();
    }
};

// 审批外出申请
const submitExamine = () => {
    itemExamineFormRef.value.validate(valid => {
        if (valid) {
            dialog.item.auditPerson = getSessionStorage('user').id;
            dialog.item.auditTime = getCurDate();
            
            // 确保auditStatus属性存在并且是数值类型
            if(dialog.item.auditStatus !== undefined) {
                // auditStatus已经是数值，不需要转换
                console.log("审批状态:", dialog.item.auditStatus);
            } else {
                // 如果还没有设置值，给一个默认值
                dialog.item.auditStatus = 1;
                console.log("设置默认审批状态:", dialog.item.auditStatus);
            }
            
            examineOutward(dialog.item).then(res => {
                if (res.flag) {
                    ElMessage.success(res.message);
                    // 刷新数据表格
                    queryOutwardVoData();
                    handleExamineClose(); // 关闭模态框
                } else {
                    ElMessage.error(res.message);
                }
            });
        } else {
            return false;
        }
    });
};

// 更新回院时间
const handleBackTimeUpdate = () => {
    itemTimeFormRef.value.validate(valid => {
        if (valid) {
            dialog.item.id = dialog.item.backTimeId;
            updateBackTime(dialog.item).then(res => {
                if (res.flag) {
                    ElMessage.success(res.message);
                    // 刷新数据表格
                    queryOutwardVoData();
                    handleTimeClose(); // 关闭模态框
                } else {
                    ElMessage.error(res.message);
                }
            });
        } else {
            return false;
        }
    });
};

// 保存外出申请
const save = () => {
    itemFormRef.value.validate(valid => {
        if (valid) {
            // 通过id判断是添加还是编辑
            if (dialog.item.id == null || dialog.item.id == "") {
                dialog.item.createTime = getCurDate();
                dialog.item.createBy = getSessionStorage("user").id;
                dialog.item.password = "000000";
                dialog.item.roleId = 2;
                dialog.item.isDeleted = 0;
                addOutward(dialog.item).then(res => {
                    if (res.flag) {
                        ElMessage.success(res.message);
                        // 刷新数据表格
                        queryOutwardVoData();
                        handleClose(); // 关闭模态框
                    } else {
                        ElMessage.error(res.message);
                    }
                });
            }
        } else {
            return false;
        }
    });
};

// 删除外出申请
const del = (id) => {
    ElMessageBox.confirm("确定删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
    })
        .then(() => {
            delOutward({ id: id }).then(res => {
                if (res.flag) {
                    ElMessage({
                        type: "success",
                        message: res.message
                    });
                    // 重载表格
                    queryOutwardVoData();
                }
            });
        })
        .catch(() => {});
};

// api-查询客户信息列表-分页
const fetchKhxxList = () => {
    getKhxxList(condition).then(res => {
        khxxList.value = res.data.records;
        customerList.value = res.data.records;
        page.total = res.data.total; // 总记录数
        page.pageSize = res.data.size; // 每页显示条数
        page.currentPag = res.data.current; // 当前页码
        page.pagCount = res.data.pages; // 总页数
    });
};

// api-查询外出申请记录
const queryOutwardVoData = () => {
    queryOutwardVo(conditionRecord).then(res => {
        outwardList.value = res.data.records;
        pageRecord.total = res.data.total; // 总记录数
        pageRecord.pageSize = res.data.size; // 每页显示条数
        pageRecord.currentPag = res.data.current; // 当前页码
        pageRecord.pagCount = res.data.pages; // 总页数
    });
};

// 页面加载时初始化
onMounted(() => {
    roleId.value = getSessionStorage('user').roleId;
    conditionRecord.userId = roleId.value === 1 ? '' : getSessionStorage('user').id;
    condition.userId = roleId.value === 1 ? '' : getSessionStorage('user').id;
    fetchKhxxList();
    queryOutwardVoData();
});
</script>

<style scoped>
.table-main {
  height: 600px;
  border: 1px solid #d4c5c5;
}
.table-main .table-main-header {
  height: 50px;
  background-color: #3ca2e0;
  color: #fff;
  font-size: 20px;
  font-family: "Microsoft YaHei";
  line-height: 50px;
}
</style>